package b1w1nn1ng.crossf1t.business;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import b1w1nn1ng.crossf1t.db.Database;

public class Timed extends Workout {
	private int time;

	public Timed(int userID, boolean prescribed, Calendar date) throws SQLException, ClassNotFoundException {
		this.userID = userID;
		this.type = "timed";
		exercises = new ArrayList<Exercise>();
		this.prescribed = prescribed;
		this.cal = date;
		Workout.incrementWorkoutCount(userID);
	}

	public Timed(int userID, int time, ArrayList<Exercise> exercises, boolean prescribed, Calendar cal) throws SQLException, ClassNotFoundException{
		this.userID = userID;
		this.time = time;
		this.type = "Timed";
		this.prescribed = prescribed;
		this.cal = cal;
		this.exercises = exercises;
		Workout.incrementWorkoutCount(userID);
	}

	public String toHTML() {
		StringBuilder ret = new StringBuilder();
		ret.append("Workout type: "+type+"<br />");
		ret.append("Date: "+CalendarDisplay.dateToString(cal)+"<br />");
		ret.append("Time: "+time+"<br />");
		ret.append("<br />Exercises: <br />");
			for(Exercise e : exercises) 
				ret.append(e.toHTML()+"<br />");
		ret.append(prescribed?"Performed as prescribed\n":"Not performed as prescribed\n");
		return ret.toString();
	}
	
//TODO oren do this make it work for exercises
	@Override
	public boolean isPr(int id, String type, Exercise[] exercises, int value)  throws Exception{
		Workout w = getPR(id, type,exercises);
		if(! (w instanceof Timed))
			throw new Exception("getPR did not return an Timed object");

		return ((Timed)w).time == value;
	}		

	public int getTime() {
		return time;
	}


	public void setTime(int time) {
		this.time = time;
	}

	@Override
	public int compareTo(Workout o) {
		double diff = this.time-((Timed) o).getTime();
		
		//the lower the time the better. so we return 1 if the difference is below 0
		if(diff<0)
			return 1;
		else
		if(diff==0)
			return 0;
		//if(diff>0)
		return -1;
	}

	@Override
	public void writeToDatabase() {
		try {
			Database.addWorkout(this);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}